﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Agile;
using Microsoft.AspNetCore.Authorization;

namespace Microsoft.AspNetCore.Mvc {
    /// <summary>
    /// GetTreeGridJson
    /// GetGridJson
    /// GetFormJson
    /// SubmitForm
    /// DeleteForm
    /// UpdateField
    /// Switch
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    [Authorize]
    public class BaseController<TEntity>:BaseController where TEntity : Entity {
        /// <summary>
        /// 身份信息
        /// </summary>
        protected ILoginInfo loginInfo { get; set; }
        protected IDbSession DBA { get; set; }
        /// <summary>
        /// cotr
        /// </summary>
        protected BaseController() {
            loginInfo = EngineContext.Current.Resolve<ILoginInfo>();
            DBA = DbFactory.DbHelper();
        }

        public IRepository<TEntity> Repository {
            get {
                var repo = Service<IRepository<TEntity>>();
                return repo;
            }
        }
        #region CURD
        public virtual IActionResult GetAll(string strWhere = "") {
            var data = Repository.FindAll(strWhere);
            return Content(data.ToJson());
        }
        /// <summary>
        /// 获取树形JSON
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HttpGet]
        public virtual IActionResult GetTreeJson() {
            if(EntityHelper.IsTreeEntity(typeof(TEntity))) {
                var data = Repository.FindAll().ToList();
                var treeList = new List<TreeViewModel>();
                for(int i = 0;i < data.Count;i++) {
                    TEntity item = data[i];
                    TreeEntity treeEntity = item as TreeEntity;
                    TreeViewModel tree = new TreeViewModel();
                    bool hasChildren = Repository.FindAll("ParentID='" + item.ID + "'").ToList().Count == 0 ? false : true;
                    tree.id = item.ID;
                    tree.text = treeEntity.Name;
                    tree.value = item.ID;
                    tree.parentId = treeEntity.ParentID;
                    tree.isexpand = true;
                    tree.complete = true;
                    tree.checkstate = i == 0 ? 1 : 0;
                    tree.hasChildren = hasChildren;
                    treeList.Add(tree);
                }
                return Content(treeList.TreeViewJson());
            } else {
                return Content("实体类没有继承TreeEntity类");
            }
        }
        /// <summary>
        /// 获取表格树形JSON
        /// </summary>
        [HttpPost]
        [HttpGet]
        public virtual IActionResult GetTreeGridJson(string keyword) {
            if(EntityHelper.IsTreeEntity(typeof(TEntity))) {
                string whereSql = "";
                if(!string.IsNullOrWhiteSpace(keyword)) {
                    whereSql = " Name like '%" + keyword + "%'";
                }
                var data = Repository.FindAll(whereSql);
                var treeList = new List<TreeGridModel>();
                foreach(TEntity item in data) {
                    TreeEntity treeEntity = item as TreeEntity;
                    TreeGridModel treeModel = new TreeGridModel();
                    bool hasChildren = Repository.FindAll("ParentID='" + item.ID + "'").ToList().Count == 0 ? false : true;
                    treeModel.id = item.ID;
                    treeModel.isLeaf = hasChildren;
                    treeModel.parentId = treeEntity.ParentID;
                    treeModel.expanded = hasChildren;
                    treeModel.entityJson = item.ToJson();
                    treeList.Add(treeModel);
                }
                return Content(treeList.TreeGridJson());
            } else {
                return Content("实体类没有继承TreeEntity类");
            }
        }
        /// <summary>
        /// 获取表格JSON
        /// </summary>
        [HttpPost]
        [HttpGet]
        public virtual IActionResult GetGridJson(string keyword = "") {
            var data = Repository.FindAll(keyword);
            return Content(data.ToJson());
        }
        /// <summary>
        /// 获取表格JSON 带分页
        /// </summary>
        [HttpPost]
        [HttpGet]
        public virtual IActionResult GetJGridPageDataJson(Paging paging) {
            JQridPageData pageData = Repository.FindAll(paging);
            return Content(pageData.ToJson());
        }
        /// <summary>
        /// 获取表单
        /// </summary>
        [HttpPost]
        [HttpGet]
        public virtual IActionResult GetFormJson(string keyId) {
            if(string.IsNullOrWhiteSpace(keyId)) return Error("参数keyId不能为空！");
            var data = Repository.Find(keyId);
            return Content(data.ToJson());
        }
        /// <summary>
        /// 提交表单
        /// </summary>
        [HttpPost]
        public virtual IActionResult SubmitForm(TEntity module) {
            Repository.AddOrUpdate(module);
            return Success("提交成功。");
        }
        /// <summary>
        /// 删除数据
        /// </summary>
        [HttpPost]
        [HttpGet]
        public virtual IActionResult DeleteForm(string keyId) {
            if(string.IsNullOrWhiteSpace(keyId)) return Error("参数keyId不能为空！");
            Repository.Delete(keyId);
            return Success("删除成功。");
        }
        /// <summary>
        /// 更新字段
        /// </summary>
        /// <param name="keyId">ID</param>
        /// <param name="fieldName">字段名称</param>
        /// <param name="fieldValue">字段值</param>
        /// <returns></returns>
        [HttpPost]
        [HttpGet]
        public virtual IActionResult UpdateField(string keyId,string fieldName,string fieldValue) {
            if(string.IsNullOrWhiteSpace(keyId)) return Error("参数keyId不能为空！");
            if(string.IsNullOrWhiteSpace(fieldName)) return Error("参数fieldName不能为空！");
            if(string.IsNullOrWhiteSpace(fieldValue)) return Error("参数fieldValue不能为空！");

            Repository.UpdateField(keyId,fieldName,fieldValue);
            return Success("操作成功。");
        }
        /// <summary>
        /// 更新排序OrderBy
        /// </summary>
        /// <param name="keyId">ID</param>
        /// <param name="value">字段值</param>
        /// <returns></returns>
        [HttpPost]
        [HttpGet]
        public virtual IActionResult UpdateOrderBy(string keyId,string value) {
            if(string.IsNullOrWhiteSpace(keyId)) return Error("参数keyId不能为空！");
            if(string.IsNullOrWhiteSpace(value)) return Error("参数value不能为空！");
            Repository.UpdateField(keyId,"OrderBy",value);
            return Success("操作成功。");
        }
        /// <summary>
        /// 开关 Status
        /// </summary>
        [HttpPost]
        [HttpGet]
        public virtual IActionResult Switch(string keyId) {
            if(keyId == null) throw new ArgumentNullException(nameof(keyId));
            var model = Repository.Find(keyId);
            if(model != null) {
                var obj = model.GetPropertyValue("Status");
                if(obj != null) {
                    int Status = (int)obj;
                    if(Status > 0) {
                        Status = 0;
                    } else {
                        Status = 1;
                    }
                    model.SetPropertyValue("Status",Status);
                    Repository.Update(model);
                }
            }
            return Success("操作成功。");
        }
        #endregion
        
    }
}
